<!--
 * @Author: JPeng 872639397@qq.com
 * @Date: 2022-05-16 10:48:41
 * @LastEditors: JPeng 872639397@qq.com
 * @LastEditTime: 2022-05-18 21:00:25
 * @FilePath: \review-review-review\复习！！！\Ajax\发送.html
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button onclick="getRes()">发送get请求</button>
    <button onclick="postRes()">发送post请求</button>
    <script>
        function getRes() {
            let xhr = new XMLHttpRequest();
            xhr.open('get', 'http://127.0.0.1:8000/server?a=100&b=200');
            xhr.send();
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        document.body.append(xhr.response);
                    }
                }
            }
        }
        //wuhu
        function postRes() {
            const xhr = new XMLHttpRequest();
            xhr.responseType = "json"; //自动处理响应数据为json JSON.parse
            xhr.timeout = 2000; //请求超过2s就取消
            xhr.ontimeout = function () {
                alert("请求超时回调");
            }
            xhr.onerror = function () {
                alert("网络异常回调");
            }
            xhr.open('post', 'http://127.0.0.1:8000/postserver');
            xhr.send('a=100&b=200 ');
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 300) {
                    document.body.append(xhr.response);
                    console.log(xhr.response);
                }
            }
        }

        //xhr.abort() 取消正在进行的请求
    </script>
</body>

</html>